/**
 * Created by DELL on 2017/4/11.
 */
window.registerUpload=function (uploadBox,options,initImagePath) {
    var self=this;
    this.photoPath=[];
    this.maxsize = 100 * 1024;
    this.compressWidth=900;
    this.canvas=document.createElement("canvas");
    this.ctx=this.canvas.getContext('2d');
    this.orientation=0;
    this.uploadBox=$(uploadBox);
    this.uploadNotice=this.uploadBox.parent().find(".esheyi-upload-notice");
    this.compressedImageBox= this.uploadBox.find("p");
    this.delImage=this.uploadBox.find(".esheyi-upload-delete");
    this.coverMask=this.uploadBox.find(".esheyi-upload-cover");
    this.uploadUrl=common.globalHost+common.uploadBasePort;
    !!initImagePath?this.init(initImagePath):null;
    this.uploadBox.off("tap").on("tap","input[type=file]",function (ev) {
        $(this).off("change").on("change",function (e) {
            self.coverMask.show();
            // self.uploadNotice.removeClass("success").addClass("failed").html("照片读取中，请稍后...");
            // self.uploadNotice.html("照片读取中，请稍后...").show().delay(500).hide(0);
            self.uploadNotice.html("照片读取中...").show();
            if (!this.files.length){return;}
            var $this=$(this);
            var selfFile=this.files;
            var reader=new FileReader();
            
            reader.readAsDataURL(selfFile[0]);
            reader.onload=function () {
                var result = this.result;
                var img = new Image();
                img.src = result;
                img.onload = function () {
                    if(result.length<self.maxsize){
                        img = null;
                        self.localImageLoaded(result);
                        self.uploadImage(result,options,function () {
                            $this.remove();
                        });
                        return;
                    }
                    var r=EXIF.getData(img, function() {
                        self.orientation = EXIF.getTag(this, 'Orientation');
                    });
                    var base64=self.compressImage(img,self.compressWidth);
                    self.localImageLoaded(base64);
                    self.uploadImage(base64,options,function () {
                        $this.remove();
                    });
                };
            };
            e.stopPropagation();
            e.preventDefault();
            return false;
        });
        ev.stopPropagation();
        ev.preventDefault();
        return false;
    });
    this.delImage.off("touchend").on("touchend",function (e) {
        self.compressedImageBox.html("").hide();
        self.coverMask.hide();
        self.uploadNotice.html("").hide();
        !!options.deleteImage && $.isFunction(options.deleteImage) && options.deleteImage();
        $(this).hide();
        self.uploadNotice.html("");
        self.uploadBox.append('<input id="esheyi-upload-file" type="file" accept="image/*" name="">');
        e.stopPropagation();
        e.preventDefault();
        return false;
    });
};
registerUpload.prototype={
    init:function (initImagePath) {
        var self=this;
        // initImagePath=initImagePath.indexOf('http')>-1?initImagePath:common.imageHost+initImagePath;
        self.delImage.show();
        self.compressedImageBox.html('<img src="'+common.imageHost+initImagePath+'" />').show();
    },
    compressImage:function (img,compressWidth) {
        var self=this;
        var imgWidth=img.naturalWidth;
        var imgHeight=img.naturalHeight;
        // var ctxImgHeight= (compressWidth)*(imgHeight/imgWidth);
        // self.canvas.width=compressWidth;
        // self.canvas.height=ctxImgHeight;
        // self.ctx.clearRect(0, 0, compressWidth, ctxImgHeight);
        // self.ctx.fillStyle = "#fff";
        // self.ctx.fillRect(0, 0, compressWidth, ctxImgHeight);
        // self.ctx.drawImage(img,0,0,compressWidth,ctxImgHeight);
        var scale=imgWidth/imgHeight;
        var ctxImgHeight;
        // alert(self.orientation);
        if(self.orientation==8){
            ctxImgHeight= compressWidth * scale;
            self.canvas.width=compressWidth;
            self.canvas.height=ctxImgHeight;
            self.ctx.clearRect(0, 0, ctxImgHeight , compressWidth);
            self.ctx.fillStyle = "#fff";
            self.ctx.fillRect(0, 0, ctxImgHeight,compressWidth);
            self.ctx.rotate(270 * Math.PI/180);
            self.ctx.drawImage(img,0,0,-ctxImgHeight,compressWidth);

        }else if(self.orientation==6){
            ctxImgHeight= compressWidth * scale;
            self.canvas.width=compressWidth;
            self.canvas.height=ctxImgHeight;
            self.ctx.clearRect(0, 0, ctxImgHeight , compressWidth);
            self.ctx.fillStyle = "#fff";
            self.ctx.fillRect(0, 0, ctxImgHeight,compressWidth);
            self.ctx.rotate(90 * Math.PI/180);
            self.ctx.drawImage(img,0,0,ctxImgHeight,-compressWidth);

        }else if(self.orientation==3){
            ctxImgHeight= compressWidth/scale;
            self.canvas.width=compressWidth;
            self.canvas.height=ctxImgHeight;
            self.ctx.clearRect(0, 0, compressWidth, ctxImgHeight);
            self.ctx.fillStyle = "#fff";
            self.ctx.fillRect(0, 0, compressWidth, ctxImgHeight);
            self.ctx.rotate(180 * Math.PI/180);
            self.ctx.drawImage(img,0,0,-compressWidth,-ctxImgHeight);
        }else {
            ctxImgHeight= compressWidth/scale;
            self.canvas.width=compressWidth;
            self.canvas.height=ctxImgHeight;
            self.ctx.clearRect(0, 0, compressWidth, ctxImgHeight);
            self.ctx.fillStyle = "#fff";
            self.ctx.fillRect(0, 0, compressWidth, ctxImgHeight);
            self.ctx.drawImage(img,0,0,compressWidth,ctxImgHeight);
        }
        var base64 = self.canvas.toDataURL("image/jpeg",0.98);
        return base64;
    },
    localImageLoaded:function (base64) {
        var self=this;
        self.compressedImageBox.html('<img src="'+base64+'" />').show();
        // self.coverMask.show();
        // self.compressedImageBox.find("img").attr("src",base64).show();
    },
    uploadImage:function (base64,options,callback) {
        var self=this;
        var sendData= {
            fileName:"H5_"+options.fileType+"_"+new Date().getTime(),
            folder:"agent",
            agentId:options.agentId,
            uploadData:base64,
            token:options.token
        };
        $.ajax
        ({
            data:sendData,
            type: "POST",
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            dataType:"json",
            beforeSend:function(){
                // self.uploadNotice.removeClass("success").addClass("failed").html("图片上传中...");
                self.uploadNotice.html("图片上传中...").show();
                // self.uploadNotice.html("图片上传中...").show().delay(500).hide(0);

            },
            url:self.uploadUrl,
            success:function(data){
                if(typeof data==="string"){
                    data=JSON.parse(data);
                }
                self.coverMask.hide();
                self.delImage.show();
                if(data.code==0){
                    var filePath = data.res.data.filePath;
                    !!callback && $.isFunction(callback) && callback();
                    !!options.uploadSuccess && $.isFunction(options.uploadSuccess) && options.uploadSuccess(filePath);
                }else{
                    !!options.uploadFail && $.isFunction(options.uploadFail) && options.uploadFail(data);
                    if(data.code==101 ||data.code==102){
                        console.log("token为空或者token失效");
                        window.location.href='login.html';
                    }
                }

            },
            timeout:10000,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                self.coverMask.hide();
                self.delImage.show();
                self.uploadNotice.html("网络不畅，请重新上传").show();
                // self.uploadNotice.removeClass("success").addClass("failed").html("网络不畅，请重新上传");
                // self.uploadNotice.html("网络不畅，请重新上传").show().delay(500).hide(0);
            }
        });
    }
}